package com.followmeandroid;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.followmeandroid.enums.ResultCode;
import com.followmeandroid.enums.ServiceUrl;
import com.followmeandroid.messages.RegisterRequest;
import com.followmeandroid.util.JSONHttpClient;

/**
 * <p>Title: RegisterActivity</p>
 * <p>Description: This activity controls the content and
 * functionality of the Registration screen.</p>
 * @author Adam Drews
 * @email adam.drews@my.uwrf.edu
 * @date 11/19/2014
 * @team Tyler Johnson
 * @email tyler.johnson@my.uwrf.edu
 * @team Nicholas Thorp
 * @email nicholas.thorp@my.uwrf.edu
 */
public class RegisterActivity extends Activity {

    EditText etEmail, etPassword, etConfirmPassword, etFname, etLname;
    Button btnRegister;
    Context context;

    /**
     * Creates the layout for the current view. It is passed a
     * bundle of data from the previous activity.
     * @param savedInstanceState    The state of the previous activity.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // Initialize  the layout components
        context = this;
        etEmail = (EditText) findViewById(R.id.et_email);
        etEmail.setSingleLine(true);

        //firstname
        etFname = (EditText) findViewById(R.id.et_FName);
        etFname.setSingleLine(true);

        //lastname
        etLname = (EditText) findViewById(R.id.et_LName);
        etLname.setSingleLine(true);



        etPassword = (EditText) findViewById(R.id.et_password);
        etPassword.setSingleLine(true);
        etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        etConfirmPassword = (EditText) findViewById(R.id.et_confirmPassword);
        etConfirmPassword.setSingleLine(true);
        etConfirmPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        btnRegister = (Button) findViewById(R.id.btn_register_post);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            /**
             * Submits a registration request to the server when all
             * fields have been filled out correctly.
             * @param v     The current view.
             */
            @Override
            public void onClick(View v) {
                String username = etEmail.getText().toString();
                String password = etConfirmPassword.getText().toString();
                String confirm = etConfirmPassword.getText().toString();
                String fname = etFname.getText().toString();
                String lname = etLname.getText().toString();

                if (password.compareTo(confirm) == 0 && password.length() > 2) {

                    if(username.length() > 1 && fname.length() > 1 && lname.length() > 1){
                        // Execute the AsyncRegister class
                        new AsyncRegister().execute(new RegisterRequest(username, username, password,fname, lname));
                    }else{
                        Toast.makeText(context, "Check names!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "Check passwords!", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    /**
     *
     */
    protected class AsyncRegister extends AsyncTask<RegisterRequest, JSONHttpClient, Integer> {
        /**
         * The operation to be performed by the thread in the background.
         * @param params        A registration request.
         * @return result       The result from the request.
         */
        @Override
        protected Integer doInBackground(RegisterRequest... params) {
            //create a registration request

            int result = 0;

            try {
                // Call the User Authentication Method in API
                result = JSONHttpClient.PostObject(ServiceUrl.POST_REGISTER.toString(), params[0], RegisterRequest.class);


            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("AsyncLogin", e.getMessage());
            }
            return result;
        }

        /**
         * Displays a please wait pop up before the thread executes.
         */
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            Toast.makeText(context, "Please Wait...", Toast.LENGTH_SHORT).show();
        }

        /**
         * Displays the result from trying to register. This result is determined
         * be a result code received by the server.
         * If successful, returns to the Login activity.
         * @param result        The failure or success of the action.
         */
        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            //result is http result code, 200 = OK
            if (ResultCode.get(result) == ResultCode.OK) {
                Intent i = new Intent(RegisterActivity.this, LoginActivity.class);

                i.putExtra("username", etEmail.getText().toString());
                startActivity(i);
            } else {
                //make them try again!
                Toast.makeText(context, getString(R.string.register_failed), Toast.LENGTH_LONG).show();
            }
        }
    }

}
